const { dialog } = require('electron').remote
import fs from 'fs'
import path from 'path'
import { indexOf, replace } from 'lodash'
import { Segment, useDefault } from 'segmentit'

const localPath = process.env.VUE_APP_LOCAL_PATH
const videoFileName = process.env.VUE_APP_VIDEO_FILE_NAME
const ruleFileName = process.env.VUE_APP_RULE_FILE_NAME
let segmentit = null

/**
 * 选择文件
 * @param {string} openType 打开方式 ['openFile', 'openDirectory']
 * @param {Array} paths 路径
 * @returns 文件数组
 */
function selectFile(openType, paths = []) {
    const typeList = ['openFile', 'openDirectory']
    const videoTypes = ['mkv', 'avi', 'mp4', 'rmvb']
    let dirPath = ''
    try {
        let list = paths
        if (list.length == 0) {
            list = dialog.showOpenDialogSync({
                title: '选择文件/文件夹',
                filters: [{ name: 'Movies', extensions: videoTypes }],
                properties: [openType, 'multiSelections'],
            })
        }
        const res = []
        // 删除文件类型
        const delExtname = (fileName) => {
            const extname = path.extname(fileName)
            return replace(fileName, extname, '')
        }
        if (list) {
            if (openType === typeList[0]) {
                dirPath = list[0]
                for (const path of list) {
                    res.push({
                        name: delExtname(mySplit(path, '\\')),
                        path,
                    })
                }
            } else if (openType === typeList[1]) {
                for (const path of list) {
                    dirPath = list[0]
                    const files = fs.readdirSync(path)
                    for (const file of files) {
                        if (indexOf(videoTypes, mySplit(file, '.')) !== -1) {
                            const name = delExtname(file)
                            res.push({
                                key: name,
                                name,
                                path: `${path}\\${file}`,
                            })
                        }
                    }
                }
            }
        }
        return { dirPath, files: res }
    } catch (e) {
        console.log(e)
        return { dirPath, files: [] }
    }
}

function mySplit(arr, separator, i = 1) {
    const list = arr.split(separator)
    return list[list.length - i]
}

/**
 * 从文件中读取数据
 * @param {string} type ['video', 'rule']
 * @return {Object}
 */
function readData(type) {
    const fileName = type == 'video' ? videoFileName : ruleFileName
    createDir()
    const files = fs.readdirSync(localPath)
    console.log(files)
    if (!files.find((v) => v == fileName)) {
        fs.writeFileSync(`${localPath}\\${fileName}`, '')
    }
    const res = fs.readFileSync(`${localPath}\\${fileName}`, 'utf-8')
    return res != '' ? JSON.parse(res) : {}
}

function createDir() {
    if (!fs.existsSync(localPath)) {
        fs.mkdirSync(localPath, { recursive: true })
    }
}

/**
 * 写入数据到文件
 * @param {Array} data
 * @param {string} key 数据的key值
 * @param {string} type ['video', 'rule']
 * @param {boolean} overwrite 覆写
 * @return {boolean} true or false
 */
function writeData(data, key, type, overwrite = false) {
    createDir()
    const fileData = readData(type)
    if (!overwrite && fileData[key]) {
        fileData[key] = fileData[key].concat(data)
    } else {
        fileData[key] = data
    }
    const fileName = type == 'video' ? videoFileName : ruleFileName
    try {
        fs.writeFileSync(`${localPath}\\${fileName}`, JSON.stringify(fileData))
    } catch (e) {
        return false
    }
    return true
}

async function segmentText(text = '') {
    if (!segmentit) {
        segmentit = await useDefault(new Segment())
    }
    return await segmentit.doSegment(text, {
        stripPunctuation: true,
    })
}

/**
 * 删除文件的数据
 * @param {Array} id 数据id
 * @param {string} key 数据的key值
 * @param {string} type ['video', 'rule']
 */
function delData(idList, key, type) {
    let fileData = readData(type)
    if (fileData[key]) {
        for (let i = 0; i < idList.length; i++) {
            for (let j = 0; j < fileData[key].length; j++) {
                if (fileData[key][j].id == idList[i]) {
                    fileData[key].splice(j, 1)
                    idList.splice(i, 1)
                    j--
                    i--
                }
            }
        }
    }
    return writeData(fileData[key], key, type, true)
}

/**
 * 打开文件夹
 * @return {Array} 文件夹数组
 */
function selectPath() {
    let list = dialog.showOpenDialogSync({
        title: '添加文件夹',
        filters: [{ name: 'Movies' }],
        properties: ['openDirectory', 'multiSelections'],
    })
    if (list) {
        return list.map((v) => {
            return v.replaceAll('\\', '/')
        })
    } else {
        return []
    }
}

/**
 * 删除文件
 * @param {string} type ['video', 'rule']
 * @return {boolean}
 */
function delFile(type) {
    const fileName = type == 'video' ? videoFileName : ruleFileName
    try {
        fs.unlinkSync(`${localPath}\\${fileName}`)
        return true
    } catch (e) {
        console.log(e)
        return false
    }
}

export { selectFile, segmentText, readData, writeData, delData, selectPath, delFile }
